package com.hfb.mashibing.alip8.juc.c020;


import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * Phaser-阶段:(控制某些线程在某些阶段执行)
 *   一般用不到，用在遗传算法中
 */

public class T09_TestPhaser2 {
    static Random r = new Random();
    static Phaser phaser = new MarriagePhaser();

    public static void milliSleep(int millis) {
        try {
            TimeUnit.MILLISECONDS.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        phaser.bulkRegister(7);
        for (int i = 0; i < 5; i++) {
            new Thread(new Person("p " + i)).start();
        }
        new Thread(new Person("新娘")).start();
        new Thread(new Person("新郎")).start();
    }

    static class MarriagePhaser extends Phaser {
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase) {
                case 0:
                    System.out.println("所有人到到齐了 "+registeredParties);
                    System.out.println();
                    return false;
                case 1:
                    System.out.println("所有人吃完了 "+registeredParties);
                    System.out.println();
                    return false;
                case 2:
                    System.out.println("所有人离开了 "+registeredParties);
                    System.out.println();
                    return false;
                case 3:
                    System.out.println("婚礼结束！新娘新郎抱抱，进洞房。。。"+registeredParties);
                    return true;
                default:
                    return true;
            }
        }
    }

    static class Person implements Runnable{
        private String name;
        public Person(String name) {
            this.name = name;
        }

        public void arrive() {
            milliSleep(r.nextInt(1000));
            System.out.println(name + " 到到了");
            phaser.arriveAndAwaitAdvance();
        }

        public void eat() {
            milliSleep(r.nextInt(1000));
            System.out.println(name + " 吃完了");
            phaser.arriveAndAwaitAdvance();
        }

        public void leave() {
            if (!name.equals("新娘") && !name.equals("新郎")) {
                milliSleep(r.nextInt(1000));
                System.out.println(name + " 离开了");
            }
            phaser.arriveAndAwaitAdvance();
        }
        public void hug() {
            if (name.equals("新娘") ||  name.equals("新郎")) {
                milliSleep(r.nextInt(1000));
                System.out.println(name + " 抱抱后洞房了。。。");
            }
            phaser.arriveAndAwaitAdvance();
        }

        @Override
        public void run() {
            arrive();

            eat();

            leave();

            hug();
        }
    }
}
